import React, { Component, ComponentClass } from 'react';
import Taro from '@tarojs/taro';
import {View, Image, ScrollView} from '@tarojs/components'
import {AtDrawer, AtIcon, AtInput} from 'taro-ui'
import {connect} from 'react-redux'
import {CityLocation, PlatformSet, SubCategory, Good} from '../../utils/server.interface'
import {platform} from '../../utils/platform-settting.service'
import {http} from '../../utils/http'
import {
  IDENTITY_IS_SELLER,
  LIST_CATEGORY,
  RESOURCE_URL,
  SCAN_BIND_SELLER, TARO_ENV,
  UPDATE_USER_SHARE_DATE
} from '../../constants/api'
import fetchNewGoodsList from "../../utils/fetchNewGoodsList";
import Headercar from '../components/header-car/header-car'
import SmallGoodsCar from '../components/small-goods-car/small-goods-car'
import {user} from '../../utils/user.service'
import SupportBar from '../../components/support-bar/support-bar'
import {getHeadTop, vcmonitor} from "../../utils/tools";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import Share from "../../components/share/share";
import './index.scss'

type PageStateProps = {
  location: CityLocation
}
type PageDispatchProps = {}
type PageOwnProps = {}
type PageState = {
  linkUri: string
  searchText: string
  isAll: boolean
  isActive: boolean
  loadMoreStatus: 'more' | 'noMore' | 'loading'
  platformSet: PlatformSet
  goods: Good[]
  categoryId: number
  categoryIdOld: number
  depth: number
  subCategory: SubCategory[]
  isClose: boolean
  searchBarTop: number
  loading: boolean
  type: 0 | 1 | 2 | 3
  drawerShow: boolean
  isUser: boolean
  risePrice: any
  endPrice: any
  sizeVolume: any
  star: any
}
type IProps = PageStateProps & PageDispatchProps & PageOwnProps

interface Index {
  props: IProps
}

@connect(({location}) => ({
  location
}), (dispatch) => ({}))

class Index extends Component {
  state: PageState = {
    linkUri: '',
    searchText: '',
    isAll: true,
    loadMoreStatus: 'loading',
    platformSet: {
      isShowServicePhone: 1,
      platformName: '',
      platformServicePhone: '',
      platformSellerType: 0,
      sellerRegType: 0
    },
    goods: [],
    categoryId: 0,
    isActive: true,
    categoryIdOld: 0,
    depth: 0,
    subCategory: [],
    searchBarTop: 0,
    isClose: true,
    isUser: true,
    loading: true,
    type: 0,
    drawerShow: false,
    risePrice: '',
    endPrice: '',
    sizeVolume: '',
    star: ''
  }
  page = 1
  shareParams = ''

  async UNSAFE_componentWillMount() {
    const categoryId = parseInt(Taro.getCurrentInstance().router.params.category) || 0
    this.setState({categoryIdOld: categoryId})
    const headTop = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 30) : (headTop.statusBar + headTop.top + 32)
    this.setState({categoryId, searchBarTop})
    const platformSet = await platform.getSetting()
    const goods = await this.getGoods(this.page, categoryId)
    const data = (await http.HGet(LIST_CATEGORY, {c: categoryId, type: 4, category: categoryId})) || {}
    if (data.data.some((item) => item.id === categoryId)) {
      this.setState({isActive: false})
    }
    if (platformSet) {
      if (platformSet.platformName) {
        Taro.setNavigationBarTitle({
          title: platformSet.platformName
        })
      }
      this.setState({platformSet, goods, loading: false, subCategory: data.data, isAll: data.is_all})
    } else {
      this.setState({goods, loading: false, subCategory: data.data, isAll: data.is_all})
    }
    if (data.data.length > 0) {
      this.setState({depth: data.data[0].depth})
    }
  }

  async componentDidShow() {
    vcmonitor(this)
    this.shareParams = await user.getSellerParams()
    let link = '/common/product/index?' + this.shareParams
    if (process.env.TARO_ENV === 'h5') {
      link = window.location.origin + link
      const shareData = {
        title: platform.info.platformName,
        desc: '商品',
        link,
        imgUrl: platform.info.platformLogo
      }
      h5Wx.share(shareData)
    } else {
      link += `&sKey=${Taro.getStorageSync('sKey' || '')}`
    }
    let isUser = true
    if (process.env.DISTINGUISH_IDENTITY) {
      const identityIsSeller = await http.get(IDENTITY_IS_SELLER, {})
      isUser = !identityIsSeller.isSeller
    }
    this.setState({linkUri: link, isUser})
    const bindSellerIds = Taro.getCurrentInstance().router.params.bindSellerId || ''
    const tempSellerIds = Taro.getCurrentInstance().router.params.tempSellerId || ''
    if ((bindSellerIds || tempSellerIds) && process.env.DISTINGUISH_IDENTITY) {
      http.HPost(SCAN_BIND_SELLER, { temp_seller_id: tempSellerIds, refer_seller_id: bindSellerIds });
    }
  }

  async onPullDownRefresh() {
    this.page = 1
    this.setState({loadMoreStatus: 'loading', list: []}, async () => {
      const list = await this.getGoods(this.page)
      this.setState({list}, () => {
        Taro.stopPullDownRefresh()
      })
    })
  }

  onShareAppMessage() {
    if (process.env.TARO_ENV !== 'tt') {
      http.post(UPDATE_USER_SHARE_DATE, {})
    }
    return {
      title: platform.info.platformName,
      path: this.state.linkUri
    }
  }

  async getGoods(page = 1, categoryId) {
    const goodsData = await fetchNewGoodsList.getGoodsList({
      module_type: "4",
      page: page,
      length: 10,
      data_type: 5,
      key_word: this.state.searchText,
      // region_region: this.props.location.region_id,
      region_region: "",
      region_category: categoryId === 0 ? "" : categoryId,
      risePrice: this.state.risePrice,
      endPrice: this.state.endPrice,
      sizeVolume: this.state.sizeVolume,
      star: this.state.star,
      commoditylist: 1
    });
    this.setState({ drawerShow: false})
    if (goodsData && Array.isArray(goodsData)) {
      if (goodsData.length < 10) {
        this.setState({loadMoreStatus: 'noMore'})
      } else {
        this.setState({loadMoreStatus: 'more'})
      }
      return goodsData
    } else {
      this.setState({loadMoreStatus: 'noMore'})
      return []
    }
  }

  async searchClick() {
    this.page = 1
    this.setState({loadMoreStatus: 'loading', goods: []}, async () => {
      const goods = await this.getGoods(this.page, this.state.categoryId)
      this.setState({goods})
    })
  }

  searchClear() {
    this.page = 1
    this.setState({searchText: '', loadMoreStatus: 'loading', goods: []}, async () => {
      const goods = await this.getGoods(this.page, this.state.categoryId)
      this.setState({goods})
    })
  }

  async onReachBottom() {
    if (this.state.loadMoreStatus != 'noMore') {
      this.setState({loadMoreStatus: 'loading'})
      const old = this.state.goods
      this.page++
      const newData = await this.getGoods(this.page, this.state.categoryId)
      this.setState({goods: [...old, ...newData]})
    }
  }

  inputChange(value) {
    this.setState({searchText: value})
  }

  subCategoryClick(id) {
    this.setState({categoryId: id, loadMoreStatus: 'loading', goods: []}, async () => {
      this.page = 1
      const goods = await this.getGoods(this.page, id)
      this.setState({goods})
    })
  }

  openList(index, val) {
    const {subCategory} = this.state
    subCategory[index]['open'] = val
    this.setState({subCategory})
  }

  openLabel(item) {
    this.page = 1
    this.setState({categoryId: item.id, loadMoreStatus: 'loading', goods: []}, async () => {
      const goods = await this.getGoods(this.page, item.id)
      this.setState({goods})
    })
  }

  async categoryClick(id, depth) {
    this.page = 1
    let data
    if (depth === 0) { // 全部
      if (this.state.depth === 2) { // 三级
        // 没有下级
        const goods = await this.getGoods(this.page, this.state.categoryIdOld)
        this.setState({goods, isActive: true, categoryId: this.state.categoryIdOld})
      } else if (this.state.depth === 1) { // 有下级
        this.setState({isActive: true, categoryId: 0, goods: []})
        data = (await http.HGet(LIST_CATEGORY, {c: id, type: 4, category: 0, depth})) || {}
        if (data.data.length > 0) {
          const goods = await this.getGoods(this.page, this.state.categoryIdOld)
          if (goods.length > 0) {
            this.setState({goods, isAll: data.is_all, subCategory: data.data})
          }
        }
      }
    } else {
      if (depth === 2) { // 没有下架
        const goods = await this.getGoods(this.page, id)
        this.setState({isActive: false, goods, categoryId: id})
      } else { // 有下级
        data = await http.HGet(LIST_CATEGORY, {c: id, type: 4, depth})
        if (data && data.data.length > 0) {
          this.setState({goods: [], categoryId: id, isActive: false})
          const goods = await this.getGoods(this.page, id)
          if (goods.length > 0) {
            if (data.data[0].id !== this.state.subCategory[0].id) {
              this.setState({categoryId: 0, isActive: true, isAll: data.is_all, subCategory: data.data})
            }
            this.setState({goods})
          }
        }
      }
    }
  }

  handlerSetData(label, val) {
    this.setState({[label]: val})
  }

  resetSearch() {
    this.setState({
      risePrice: '',
      endPrice: '',
      sizeVolume: '',
      star: ''
    }, async () => {this.searchClick()})
  }

  setDrawerShow() {
    const {drawerShow} = this.state
    this.setState({drawerShow: !drawerShow, isClose: true})
  }

  render() {
    const {
      linkUri,
      loading,
      loadMoreStatus,
      searchBarTop,
      goods,
      subCategory,
      categoryId,
      type,
      isClose,
      isAll,
      isActive,
      drawerShow,
      risePrice,
      endPrice,
      sizeVolume,
      isUser,
      star
    } = this.state
    return (
      <View className='productRoot'>
        <View>
          <GzhAuth />
          {TARO_ENV !== 'h5' && TARO_ENV !== 'tt' && <View className='head-bg' style={`height: ${searchBarTop}Px;`}>
            <Headercar color='#333' />
          </View>}
          {type === 0 && <View className='label-nav' style={`top: ${searchBarTop}Px;`}>
            <ScrollView className='scroll-view' enable-flex scrollX style={`${(process.env.P_ENV === 'vc' || process.env.P_ENV === 'kunxin') ? 'width: 90%;' : ''}`}>
              <View className={`nav-box ${!isClose && 'nav-box-open'}`}>
                {isAll && <View className={`item ${isActive ? 'active' : ''}`} onClick={this.categoryClick.bind(this, 0, 0)}>全部</View>}
                <View className='subcategory'>
                  {subCategory.map(item => <View key={item.id}
                                                 className={`item ${item.id == categoryId ? 'active' : ''}`}
                                                 onClick={this.categoryClick.bind(this, item.id, item.depth)}
                  >{item.name}</View>)}
                </View>
                <View className={`indicator ${process.env.TARO_ENV}`} onClick={() => {
                  this.setState({isClose: !isClose, drawerShow: false})
                }}
                >
                  <AtIcon value='chevron-down' size='16' color='#777' className={`close ${isClose && 'open'}`} />
                </View>
              </View>
            </ScrollView>
            {(process.env.P_ENV === 'vc' || process.env.P_ENV === 'kunxin') && <AtIcon size='18' value='icon icon-shaixuan-01' className='iconClass' onClick={this.setDrawerShow.bind(this)} />}
          </View>}
          {/*{!!drawerShow && <View className='head-bg' style={`height: ${searchBarTop}Px;`}>*/}
            <AtDrawer
              show={drawerShow}
              mask
              right
              width='70%'
            >
              <View className='scrrent'>
                <ScrollView
                  className={process.env.TARO_ENV === 'h5' ? 'scrollview' : 'scrollview scrollviewWeapp'}
                  scrollY
                  scrollWithAnimation
                >
                  <View className='scrrent-item'>
                    <View className='scrrent-item-title'>价格区间</View>
                    <View className='scrrent-item-content'>
                      <View>
                        <AtInput
                          className='priceInput'
                          name='risePrice'
                          type='digit'
                          placeholder='最低价'
                          value={risePrice}
                          border={false}
                          maxLength={15}
                          onChange={this.handlerSetData.bind(this, 'risePrice')}
                        />
                      </View>
                      <View className='line'>-</View>
                      <View>
                        <AtInput
                          className='priceInput'
                          name='endPrice'
                          type='digit'
                          placeholder='最高价'
                          value={endPrice}
                          border={false}
                          maxLength={15}
                          onChange={this.handlerSetData.bind(this, 'endPrice')}
                        />
                      </View>
                    </View>
                  </View>
                  <View className='scrrent-item'>
                    <View className='scrrent-item-title'>销量排序</View>
                    <View className='scrrent-item-label'>
                      <View className={`label ${sizeVolume === 0 ? 'active' : ''}`} onClick={this.handlerSetData.bind(this, 'sizeVolume', 0)}>由少到多</View>
                      <View className={`label ${sizeVolume == 1 ? 'active' : ''}`} onClick={this.handlerSetData.bind(this, 'sizeVolume', 1)}>由多到少</View>
                    </View>
                  </View>
                  <View className='scrrent-item'>
                    <View className='scrrent-item-title'>品质</View>
                    <View className='scrrent-item-label'>
                      <View className={`label ${star == 5 ? 'active' : ''}`} onClick={this.handlerSetData.bind(this, 'star', 5)}>5星好评</View>
                      <View className={`label ${star == 4 ? 'active' : ''}`} onClick={this.handlerSetData.bind(this, 'star', 4)}>4星以上</View>
                      <View className={`label ${star == 3 ? 'active' : ''}`} onClick={this.handlerSetData.bind(this, 'star', 3)}>3星以上</View>
                    </View>
                  </View>
                  <View className='scrrent-item scrrent-item-btn'>
                    <View className='btn btn-reset' onClick={() => this.resetSearch()}>
                      重置
                    </View>
                    <View
                      className='btn btn-search'
                      style={`background-color: ${process.env.mainColor}; color: #fff;`}
                      onClick={() => this.searchClick()}
                    >
                      搜索
                    </View>
                  </View>
                </ScrollView>
              </View>
            </AtDrawer>
          {/*</View>}*/}
          <View className='goods-box'>
            <SmallGoodsCar loading={loading} data={goods} />
          </View>
          {goods.length == 0 && loadMoreStatus != 'loading' && <View className='listNull'>
            <Image src={`${RESOURCE_URL}/resources/images/shopnull.png`} mode='widthFix' />
            <View className='text'>什么都没有,去看看别的吧~</View>
          </View>}
          {linkUri && process.env.P_ENV !== 'lx' && <Share isUser={isUser} linkUri={linkUri} />}
        </View>
        <SupportBar />
      </View>
    )
  }
}

export default Index as ComponentClass<PageOwnProps, PageState>
